﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using VOL.Core.Filters;
using VOL.Core.Utilities;
using VOL.Domain.IServices;
using VOL.Entity.DomainModels;
using VOL.Domain.Dto;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System;
using VOL.Core.Extensions;
using Newtonsoft.Json;

namespace VOL.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductionManagementController : ControllerBase
    {
        private readonly IProcessService _processService;

        public ProductionManagementController(IProcessService processService)
        {
            _processService = processService;
        }

        /// <summary>
        /// 分页获取工艺路线数据
        /// </summary>
        /// <param name="searchDto">查询条件和分页参数</param>
        /// <returns>分页数据</returns>
        [HttpGet("getProcessPageData")]
        public async Task<WebResponseContent> GetProcessPageData([FromQuery] ProcessSearchDto searchDto)
        {
            return await _processService.GetProcessPageData(searchDto);
        }

        /// <summary>
        /// 创建工艺路线
        /// </summary>
        /// <param name="process">工艺路线信息</param>
        /// <returns>创建结果</returns>
        [HttpPost("addProcess")]
        public async Task<WebResponseContent> AddProcess([FromBody] Process process)
        {
            return await _processService.AddProcess(process);
        }

        /// <summary>
        /// 修改工艺路线
        /// </summary>
        /// <param name="process">工艺路线信息</param>
        /// <returns>修改结果</returns>
        [HttpPost("updateProcess")]
        public async Task<WebResponseContent> UpdateProcess([FromBody] Process process)
        {
            return await _processService.UpdateProcess(process);
        }

        /// <summary>
        /// 批量删除工艺路线
        /// </summary>
        /// <param name="ids">工艺路线ID数组</param>
        /// <returns>删除结果</returns>
        [HttpPost("batchDeleteProcess")]
        public async Task<WebResponseContent> BatchDeleteProcess([FromBody] int[] ids)
        {
            return await _processService.BatchDeleteProcess(ids);
        }

        /// <summary>
        /// 分页获取组成工序数据
        /// </summary>
        /// <param name="searchDto">查询条件和分页参数</param>
        /// <returns>分页数据</returns>
        [HttpGet("getCompositionProcessPageData")]
        public async Task<WebResponseContent> GetCompositionProcessPageData([FromQuery] CompositionProcessSearchDto searchDto)
        {
            return await _processService.GetCompositionProcessPageData(searchDto);
        }

        /// <summary>
        /// 添加组成工序
        /// </summary>
        /// <param name="compositionProcess">组成工序信息</param>
        /// <returns>添加结果</returns>
        [HttpPost("addCompositionProcess")]
        public async Task<WebResponseContent> AddCompositionProcess([FromBody] CompositionProcess compositionProcess)
        {
            return await _processService.AddCompositionProcess(compositionProcess);
        }

        /// <summary>
        /// 修改组成工序
        /// </summary>
        /// <param name="compositionProcess">组成工序信息</param>
        /// <returns>修改结果</returns>
        [HttpPost("updateCompositionProcess")]
        public async Task<WebResponseContent> UpdateCompositionProcess([FromBody] CompositionProcess compositionProcess)
        {
            return await _processService.UpdateCompositionProcess(compositionProcess);
        }

        /// <summary>
        /// 批量删除组成工序
        /// </summary>
        /// <param name="ids">组成工序ID数组</param>
        /// <returns>删除结果</returns>
        [HttpPost("batchDeleteCompositionProcess")]
        public async Task<WebResponseContent> BatchDeleteCompositionProcess([FromBody] int[] ids)
        {
            return await _processService.BatchDeleteCompositionProcess(ids);
        }

        /// <summary>
        /// 导出工艺路线数据为Excel表格
        /// </summary>
        /// <param name="searchDto">查询条件</param>
        /// <returns>Excel文件</returns>
        [HttpGet("exportProcessToExcel")]
        public async Task<IActionResult> ExportProcessToExcel([FromQuery] ProcessSearchDto searchDto)
        {
            try
            {
                // 设置分页为最大值，确保导出所有数据
                searchDto.Page = 1;
                searchDto.PageSize = 10000;

                // 调用现有方法获取数据
                var result = await _processService.GetProcessPageData(searchDto);
                if (!result.Status)
                {
                    return BadRequest(result.Message);
                }

                // 处理返回的数据
                var excelData = new List<Dictionary<string, object>>();
                
                // 使用JSON序列化和反序列化处理数据
                try
                {
                    // 先将结果序列化为JSON
                    string json = Newtonsoft.Json.JsonConvert.SerializeObject(result.Data);
                    System.Diagnostics.Debug.WriteLine($"JSON数据: {json}");
                    
                    // 反序列化为字典
                    var dataDict = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
                    
                    if (dataDict != null && dataDict.ContainsKey("rows"))
                    {
                        // 获取rows数组
                        var rowsJson = Newtonsoft.Json.JsonConvert.SerializeObject(dataDict["rows"]);
                        var rows = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(rowsJson);
                        
                        if (rows != null)
                        {
                            foreach (var item in rows)
                            {
                                var row = new Dictionary<string, object>
                                {
                                    { "工艺路线编号", GetSafeValue(item, "ProcessCode") },
                                    { "工艺路线名称", GetSafeValue(item, "ProcessName") },
                                    { "状态", GetSafeValue<int>(item, "Status") == 1 ? "启用" : "禁用" },
                                    { "工艺路线说明", GetSafeValue(item, "ProcessDescription") },
                                    { "备注", GetSafeValue(item, "ProcessDesc") },
                                };
                                excelData.Add(row);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"处理数据结构出错: {ex.Message}");
                    return BadRequest($"处理数据失败: {ex.Message}");
                }

                // 如果没有数据，返回提示
                if (excelData.Count == 0)
                {
                    return NotFound("没有找到符合条件的数据");
                }

                // 生成Excel文件
                string fileName = $"工艺流程数据_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                
                try 
                {
                    // 直接获取Excel文件的字节数组
                    byte[] fileBytes = VOL.Core.Extensions.ExportExcel.Export(excelData, fileName);
                    
                    // 返回文件
                    return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
                }
                catch (Exception ex)
                {
                    return BadRequest($"导出失败：{ex.Message}");
                }
            }
            catch (Exception ex)
            {
                return BadRequest($"导出失败：{ex.Message}");
            }
        }
        
        /// <summary>
        /// 安全获取字典值
        /// </summary>
        private string GetSafeValue(Dictionary<string, object> dict, string key)
        {
            if (dict == null) return "";
            
            if (dict.TryGetValue(key, out object value) && value != null)
            {
                return value.ToString();
            }
            return "";
        }
        
        /// <summary>
        /// 安全获取字典值并转换为指定类型
        /// </summary>
        private T GetSafeValue<T>(Dictionary<string, object> dict, string key) where T : struct
        {
            if (dict == null) return default;
            
            if (dict.TryGetValue(key, out object value) && value != null)
            {
                try
                {
                    if (value is Newtonsoft.Json.Linq.JValue jValue)
                    {
                        return jValue.ToObject<T>();
                    }
                    return (T)Convert.ChangeType(value, typeof(T));
                }
                catch
                {
                    return default;
                }
            }
            return default;
        }
    }
}
